package com.zhu.storesmanager;

import java.util.ArrayList;
import java.util.List;

import com.zhu.storesmanager.models.DataItem;
import com.zhu.storesmanager.models.SyncModel;
import com.zhu.storesmanager.models.VisitTaskInfo;
import com.zhu.storesmanager.network.HttpConnectionMethod;
import com.zhu.storesmanager.network.HttpUtil;
import com.zhu.storesmanager.network.NetworkCallback;
import com.zhu.storesmanager.network.ParseNetworkData;
import com.zhu.storesmanager.network.PutSupervisorVisitData;
import com.zhu.storesmanager.utils.Actions;
import com.zhu.storesmanager.utils.DataUtils;
import com.zhu.storesmanager.utils.Log;
import com.zhu.storesmanager.views.ChoiceView;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 管理员查询页面
 */
public class AdminSearchActivity extends Activity implements OnClickListener , ChoiceView.DataChangeListener{

	private final static int MSG_REGION_FAIL = 0;
	private final static int MSG_REGION_SUCCESS = 1;
	private final static int MSG_CITY_SUCCESS = 2;
	private final static int MSG_STORE_SUCCESS = 3;

	private final static int NETWORK_DIALOG = 0; //网络进度框

	private ChoiceView mQudaoChoiceView = null; //渠道
	private ChoiceView mFenbanChoiceView = null; //分办
	private ChoiceView mCityChoiceView = null; //城市
	private ChoiceView mQuyuChoiceView = null; //区域
	private EditText mNameEditText = null; //门店名字输入框
	private SyncModel.QueryRegionResult mQueryRegionResult = null; //区域数据
	private SyncModel.QueryCityResult mQueryCityResult = null; //城市数据
	private SyncModel.QueryCounterResult mQueryCounterResult = null; //门店数据
	private LinearLayout mBodyView = null; //列表内容数据

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_admin_search);

		setupViews();
		initData();
	}

	/**
	 * 初始化界面
	 */
	private void setupViews(){
		((TextView) findViewById(R.id.title_text)).setText(R.string.main_search);
		mQuyuChoiceView = (ChoiceView) findViewById(R.id.admin_search_quyu);
		mQuyuChoiceView.setDataChangeListener(this);
		mFenbanChoiceView = (ChoiceView) findViewById(R.id.admin_search_fenban);
		mFenbanChoiceView.setDataChangeListener(this);
		mCityChoiceView = (ChoiceView) findViewById(R.id.admin_search_city);
		mQudaoChoiceView = (ChoiceView) findViewById(R.id.admin_search_qudao);
		mNameEditText = (EditText) findViewById(R.id.admin_search_nameedit);
		findViewById(R.id.admin_search_button).setOnClickListener(this);
		findViewById(R.id.bottom_back).setOnClickListener(this);
		mBodyView = (LinearLayout)findViewById(R.id.body);
	}

	/**
	 * (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v != null){
			switch(v.getId()){ //查询
				case R.id.admin_search_button:
					startSearch();
					break;
				case R.id.bottom_back: //返回
					finish();
					break;
				case R.id.rowcontent: //选择门店
					SyncModel.ResCounter counter = (SyncModel.ResCounter)v.getTag();
					gotoVisitListActivity(counter.Code, counter.Name);
					break;
			}
		}
	}

	/**
	 * 初始化数据 
	 */
	private void initData(){
		showDialog(NETWORK_DIALOG);
		//请求区域数据
		new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
            	mQueryRegionResult = ParseNetworkData.parseRegionResult(result);
            	dismissDialog(NETWORK_DIALOG);
            	if(mQueryRegionResult != null && mQueryRegionResult.Status == SyncModel.SUCCEED){ //请求成功
            		mHandler.sendEmptyMessage(MSG_REGION_SUCCESS);
            	}else{ //请求失败
            		mHandler.sendEmptyMessage(MSG_REGION_FAIL);
            	}
            }
         }
        ).callPost(HttpUtil.getRegionUrl(), HttpUtil.getPutRegionContent(DataUtils.mUserData.mUuid));
	}

	/**
     * 联网进度提示
     */
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case NETWORK_DIALOG:
                ProgressDialog pd = new ProgressDialog(this);
                pd.setMessage(this.getString(R.string.getdata)
                        + getString(R.string.please_wait));
                pd.setCancelable(false);
                pd.setCanceledOnTouchOutside(false);
                return pd;

            default:
                break;
        }
        return super.onCreateDialog(id);
    }

    /**
     * 上传结果消息处理
     */
    private Handler mHandler = new Handler(){
    	public void handleMessage(Message msg) {
            switch (msg.what) {
            	case MSG_REGION_SUCCESS:
            		updateRegionData();
            		Actions.toastShort(AdminSearchActivity.this, R.string.success_getdata);
            		break;
            	case MSG_REGION_FAIL:
            		Actions.toastShort(AdminSearchActivity.this, R.string.fail_getdata);
            		break;
            	case MSG_CITY_SUCCESS:
            		updateCityData();
            		Actions.toastShort(AdminSearchActivity.this, R.string.success_getdata);
            		break;
            	case MSG_STORE_SUCCESS:
            		updateStoreData();
            		Actions.toastShort(AdminSearchActivity.this, R.string.success_getdata);
            		break;
            }
    	}
    };

    /**
     * 更新区域数据
     */
    private void updateRegionData(){
    	if(mQueryRegionResult.Data != null){
    		if(mQueryRegionResult.Data.Regions != null){ //更新区域数据
    			List<DataItem> regions = new ArrayList<DataItem>();
	            for(SyncModel.ResRegion region : mQueryRegionResult.Data.Regions){
	            	DataItem item = new DataItem();
	            	item.mDataId = region.Id +"";
	            	item.mDataName = region.Name;
	            	regions.add(item);
	            }
	            mQuyuChoiceView.setChoiceDataList(regions);
            }

    		if(mQueryRegionResult.Data.Channels != null){ //更新渠道数据
    			List<DataItem> channels = new ArrayList<DataItem>();
	            for(SyncModel.ResChannel channel : mQueryRegionResult.Data.Channels){
	            	DataItem item = new DataItem();
	            	item.mDataId = channel.Code;
	            	item.mDataName = channel.Name;
	            	channels.add(item);
	            }
	            mQudaoChoiceView.setChoiceDataList(channels);
            }
    	}
    }

    /**
     * (non-Javadoc)
     * @see com.zhu.storesmanager.views.ChoiceView.DataChangeListener#onDataChange(com.zhu.storesmanager.views.ChoiceView)
     */
	@Override
	public void onDataChange(ChoiceView view) {
		// TODO Auto-generated method stubActions.toastShort(AdminSearchActivity.this, R.string.success_getdata);
		if(view == mQuyuChoiceView){ //渠道数据发生变化
			mFenbanChoiceView.clearData();
			mCityChoiceView.clearData();
			updateBranchData(Integer.parseInt(mQuyuChoiceView.getSaveData()));
		}else if(view == mFenbanChoiceView){ //分办数据发生变化
			mCityChoiceView.clearData();
			startGetCity(Integer.parseInt(mFenbanChoiceView.getSaveData()));
		}
	}

	/**
	 * 更新分办数据列表
	 * @param regionId 渠道ID
	 */
	private void updateBranchData(int regionId){
		if(mQueryRegionResult.Data != null)
    	{
    		if(mQueryRegionResult.Data.Branchs != null)
            {
    			List<DataItem> barands = new ArrayList<DataItem>();
	            for(SyncModel.ResBranch branch : mQueryRegionResult.Data.Branchs){ //遍历指定区域ID的分办
	            	if(branch.RegionId == regionId){
	            		DataItem item = new DataItem();
	            		item.mDataId = branch.Id +"";
	            		item.mDataName = branch.Name;
	            		barands.add(item);
	            	}
	            }
	            mFenbanChoiceView.setChoiceDataList(barands);
            }
	    }
	}

	/**
	 * 获取城市列表
	 * @param branchId 分区ID
	 */
	private void startGetCity(int branchId){
		showDialog(NETWORK_DIALOG);
		//请求区域数据
		new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
            	mQueryCityResult = ParseNetworkData.parseCityResult(result);
            	dismissDialog(NETWORK_DIALOG);
            	if(mQueryCityResult != null && mQueryCityResult.Status == SyncModel.SUCCEED){ //请求成功
            		mHandler.sendEmptyMessage(MSG_CITY_SUCCESS);
            	}else{ //请求失败
            		mHandler.sendEmptyMessage(MSG_REGION_FAIL);
            	}
            }
         }
        ).callPost(HttpUtil.getCityUrl(), HttpUtil.getPutCityContent(DataUtils.mUserData.mUuid, branchId));
	}

	/**
	 * 更新城市列表数据
	 */
	private void updateCityData() {
		if (mQueryCityResult.Cities != null) {
			List<DataItem> citys = new ArrayList<DataItem>();
			for (SyncModel.ResCity city : mQueryCityResult.Cities) {
				DataItem item = new DataItem();
				item.mDataId = city.Code;
				item.mDataName = city.Name;
				citys.add(item);
			}
			mCityChoiceView.setChoiceDataList(citys);
		}
	}

	/**
	 * 开始查询数据
	 */
	private void startSearch(){
		String storeName = mNameEditText.getText().toString(); //门店名字
		String cityCode = mCityChoiceView.getSaveData(); //城市代码
		String channel = mQudaoChoiceView.getSaveData(); //渠道代码
		String branchCode = getBranchCode();
		Log.d("branchCode="+branchCode);
	    if(/*checkString(storeName) &&*/ checkString(cityCode) && checkString(channel)){
	    	startGetStore(branchCode, storeName, cityCode, channel);
	    }else{
	    	Actions.toastShort(AdminSearchActivity.this, R.string.search_error_input);
	    }
	}

	/**
	 * 获取分办Code
	 */
	private String getBranchCode(){
		int regionId = Integer.parseInt(mQuyuChoiceView.getSaveData());
		int branchId = Integer.parseInt(mFenbanChoiceView.getSaveData());
		for(SyncModel.ResBranch branch : mQueryRegionResult.Data.Branchs){ //遍历指定区域ID的分办
        	if(branch.RegionId == regionId && branch.Id == branchId){
        		return branch.Code;
        	}
        }
		return null;
	}

	/**
	 * 检测文本是否合法
	 * @param text 文本
	 */
	private boolean checkString(String text){
		if(text != null && text.length() > 0){
			return true;
		}
		return false;
	}


	/**
	 * 获取门店列表
	 * @param storeName 门店名字
	 * @param cityCode 城市代码
	 * @param channel 渠道号
	 * @param branchCode 分办代码
	  */
	private void startGetStore(String branchCode, String storeName, String cityCode, String channel){
		showDialog(NETWORK_DIALOG);
		//请求区域数据
		new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
            	mQueryCounterResult = ParseNetworkData.parseCounterResult(result);
            	dismissDialog(NETWORK_DIALOG);
            	if(mQueryCounterResult != null && mQueryCounterResult.Status == SyncModel.SUCCEED){ //请求成功
            		mHandler.sendEmptyMessage(MSG_STORE_SUCCESS);
            	}else{ //请求失败
            		mHandler.sendEmptyMessage(MSG_REGION_FAIL);
            	}
            }
         }
        ).callPost(HttpUtil.getCounterUrl(), HttpUtil.getPutCounterContent(DataUtils.mUserData.mUuid, branchCode, cityCode, channel, storeName));
	}

	/**
	 * 更新门店列表数据
	 */
	private void updateStoreData(){
		if(mBodyView != null){
			mBodyView.removeAllViews();
		}
		if(mQueryCounterResult.Counters != null){	            		
    		if(mQueryCounterResult.Counters != null){
    			int index = 1;
	            for(SyncModel.ResCounter counter : mQueryCounterResult.Counters){
	            	mBodyView.addView(getStoreListItem(counter, index));
	            	index++;
	            }
            }
    	}
	}

	/**
     * 获取门店列表项界面
     */
    private View getStoreListItem(SyncModel.ResCounter resCounter, int index) {
        View row = LayoutInflater.from(this).inflate(R.layout.storelist_item, null);
        View content = row.findViewById(R.id.rowcontent);
        content.setTag(resCounter);
        content.setOnClickListener(this);
        ((TextView) row.findViewById(R.id.store_xuhao)).setText(index  + "");
        ((TextView) row.findViewById(R.id.store_name)).setText(resCounter.Name);
        return row;
    }

    /**
     * @param storeId 门店ID
     * @param storeName 门店名字
     */
    private void gotoVisitListActivity(String storeId, String storeName){
    	Intent intent = new Intent();
    	intent.putExtra(AdminVisitDateActivity.STORE_ID, storeId);
    	intent.putExtra(AdminVisitDateActivity.STORE_NAME, storeName);
    	intent.setClass(this, AdminVisitDateActivity.class);
    	startActivity(intent);
    }
}
